package cn.rick.controller;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.util.SaResult;
import cn.rick.constant.Constants;
import cn.rick.entity.SysUser;
import cn.rick.entity.SysUserRole;
import cn.rick.service.ISysDeptService;
import cn.rick.service.ISysRoleService;
import cn.rick.service.ISysUserRoleService;
import cn.rick.service.ISysUserService;
import cn.rick.util.EasyExcelUtil;
import cn.rick.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author Rick
 * @date 2022-10-19 16:32
 */
@RestController
@RequestMapping(value = "/api/user")
@Api(value = "用户控制", tags = {"用户控制"})
public class UserController {

    @Resource
    private ISysUserService iSysUserService;

    @Resource
    private ISysDeptService iSysDeptService;

    @Resource
    private ISysUserRoleService iSysUserRoleService;

    @Resource
    private ISysRoleService iSysRoleService;

    /**
     * 通过用户id查询用户
     *
     * @param userId 用户id
     * @return
     */
    @ApiOperation("通过用户id查询用户")
    @GetMapping(value = "/getUserById")
    public SaResult selectAllByUserId(@RequestParam String userId) {
        SysUser byId = iSysUserService.getById(userId);
        byId.setSysDept(iSysDeptService.getById(byId.getDeptId()));
        byId.setRoles(iSysRoleService.findRolesByUserId(byId.getUserId()));
        return SaResult.data(byId);
    }

    /**
     * 通过参数获取所有用户信息
     *
     * @param user      用户实体
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param pageNum   开始页
     * @param pageSize  页大小
     * @return
     */
    @GetMapping("/getData")
    @ApiOperation("通过参数获取所有用户信息")
    public SaResult getData(SysUser user, String startDate, String endDate, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> allByParam = iSysUserService.getAllByParam(user, startDate, endDate);
        PageInfo<SysUser> pageInfo = new PageInfo<>(allByParam);
        return SaResult.data(pageInfo);
    }

    @GetMapping("/download")
    @ApiOperation("通过参数下载所有用户信息")
    public void download(SysUser user, String startDate, String endDate, HttpServletResponse response) {
        List<SysUser> allByParam = iSysUserService.getAllByParam(user, startDate, endDate);
        EasyExcelUtil.writeExcel(response, allByParam, SysUser.class, "用户信息");
    }

    @PostMapping("/save")
    @ApiOperation("保存用户")
    @Transactional(rollbackFor = Exception.class)
    public SaResult save(@RequestBody Map<String, Object> map) {
        LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
        query.eq(SysUser::getUserName, map.get("userName"));
        SysUser one = iSysUserService.getOne(query);
        if (Objects.nonNull(one)) {
            return SaResult.error("用户名已存在");
        } else {
            boolean b2 = true;
            SysUser sysUser = JSON.parseObject(JSON.toJSONString(map), SysUser.class);


            if (Objects.nonNull(map.get("userId"))) {
                LambdaQueryWrapper<SysUserRole> query2 = new LambdaQueryWrapper<>();
                query2.eq(SysUserRole::getUserId, map.get("userId"));
                iSysUserRoleService.remove(query2);

                sysUser.setUpdateTime(LocalDateTime.now());
            } else {
                sysUser.setPassword(SaSecureUtil.aesEncrypt(Constants.PASSKEY, sysUser.getPassword()));
            }

            boolean b = iSysUserService.saveOrUpdate(sysUser);

            List<Integer> roleIds = (List<Integer>) map.get("roleIds");
            if (Objects.nonNull(map.get("roleIds")) && roleIds.size() > 0) {
                List<SysUserRole> list = new ArrayList<>();
                roleIds.forEach(item -> {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(sysUser.getUserId());
                    sysUserRole.setRoleId(Long.valueOf(item));
                    list.add(sysUserRole);
                });
                b2 = iSysUserRoleService.saveBatch(list);
            }

            if (b && b2) {
                return SaResult.ok("保存成功");
            } else {
                return SaResult.error("保存失败");
            }


        }
    }

    @PostMapping("/saveInfo")
    @ApiOperation("保存当前用户基本信息")
    public SaResult saveInfo(@RequestBody SysUser sysUser) {

        sysUser.setUpdateTime(LocalDateTime.now());

        if (StringUtils.isNotEmpty(sysUser.getPassword())) {
            sysUser.setPassword(SaSecureUtil.aesEncrypt(Constants.PASSKEY, sysUser.getPassword()));
        }

        if (iSysUserService.updateById(sysUser)) {
            return SaResult.ok("保存成功");
        } else {
            return SaResult.error("保存失败");
        }

    }

    @PostMapping("/checkPassword")
    @ApiOperation("验证旧密码")
    public SaResult checkPassword(@RequestBody SysUser sysUser) {
        SysUser byId = iSysUserService.getById(sysUser.getUserId());
        if (byId.getPassword().equals(SaSecureUtil.aesEncrypt(Constants.PASSKEY, sysUser.getPassword()))) {
            return SaResult.ok("密码已确认");
        } else {
            return SaResult.error("旧密码不正确");
        }
    }

    @PostMapping("/del")
    @ApiOperation("删除用户")
    public SaResult delUser(@RequestBody Map<String, Object> map) {
        if (Objects.nonNull(map.get("userId"))) {
            Integer id = (Integer) map.get("userId");
            if (iSysUserService.removeById(id)) {
                LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(SysUserRole::getUserId, id);
                iSysUserRoleService.remove(queryWrapper);
                return SaResult.ok("删除成功");
            } else {
                return SaResult.error("删除失败，请稍后再试");
            }
        } else if (Objects.nonNull(map.get("userIds"))) {
            List<Integer> ids = (List<Integer>) map.get("userIds");

            LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(SysUserRole::getUserId, ids);
            iSysUserRoleService.remove(wrapper);

            if (iSysUserService.removeBatchByIds(ids)) {
                return SaResult.ok("批量删除成功");
            } else {
                return SaResult.error("批量删除失败，请稍后再试");
            }
        } else {
            return SaResult.error("删除用户参数出现问题，请稍后再试");
        }
    }

    @GetMapping("/getUsersBySelect")
    @ApiOperation("获取用户列表给下拉框选择")
    public SaResult getUsersBySelect() {
        List<SysUser> list = iSysUserService.list();
        return SaResult.data(list);
    }


}
